import React, { useState ,useEffect} from 'react';
import './Topic.css'; // 样式
import { ReactComponent as BookmarkIcon } from '../assets/icons/Follow.svg'; // 收藏图标
import { ReactComponent as BookmarkedIcon } from '../assets/icons/Followed.svg'; // 已收藏图标
import defaultAvatar from '../assets/images/默认头像.jpg';
import { useNavigate } from 'react-router-dom';
import { collect, uncollect } from '../api/userApi'; // 导入收藏相关的接口

const Topic = ({ topic }) => {
  const [isBookmarked, setIsBookmarked] = useState(false); // 初始化收藏状态
  const userId = localStorage.getItem('userId'); // 获取当前用户 ID
  const navigate = useNavigate();

  useEffect(() => {
    if (topic && topic.isBookmarked !== undefined) {
      setIsBookmarked(topic.isBookmarked); // 同步状态
    }
    else 
      console.log('???');
  }, [topic]);
  
  const toggleBookmark = async () => {
    const previousState = isBookmarked; // 记录原始状态
    setIsBookmarked(!isBookmarked); // 立即切换状态
    try {
      if (previousState) {
        await uncollect(userId, topic.interestId); // 取消收藏
      } else {
        await collect(userId, topic.interestId); // 执行收藏
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      setIsBookmarked(previousState); // 回滚状态
    }
  };
  

  const topicImage = topic.image ? `http://localhost:8080/${topic.image}` : defaultAvatar;

  const clickTopic = () => {
    navigate(`/topic/${topic.interestId}`); // 跳转到话题详情
  };

  return (
    <div className="topic">
      <div className="topic-header">
        <img className="topic-image" src={topicImage} alt="topic" />

        <div className="topic-info">
          <h3 className="topic-title" onClick={clickTopic}>{topic.title || '未知话题'}</h3>
          <p className="topic-description">{topic.description || '暂无话题描述'}</p>
          <span className="topic-count">收藏量: {topic.count || '0'}</span>
        </div>

        <button 
          className={`bookmark-btn ${isBookmarked ? 'bookmarked' : 'not-bookmarked'}`} 
          onClick={toggleBookmark}
        >
          {isBookmarked ? (
            <div className='bookmark-btn-inner-bookmarked'>
              <span>已收藏</span>
            </div>
          ) : (
            <div className='bookmark-btn-inner-not-bookmarked'>
              <span>收藏</span>
            </div>
          )}
          {isBookmarked ? (
            <BookmarkedIcon className="bookmark-icon" />
          ) : (
            <BookmarkIcon className="bookmark-icon" />
          )}
        </button>
      </div>
    </div>
  );
};

export default Topic;
